//
//  ZFScnViewController.swift
//  map
//
//  Created by fyzq on 2024/2/22.
//

import UIKit
import SceneKit
import Kingfisher
class ZFScnViewController: UIViewController {
    
    var scnView:SCNView!
    var cameraNode:SCNNode!
    var panoramaNode:SCNNode!
    
    //记录位置
    var lastPoint_x:CGFloat = 0
    var lastPoint_y:CGFloat = 0
    
    //记录角度
    var fingerRotationY:CGFloat = 0
    var fingerRotationX:CGFloat = 0
    var netRotation:CGFloat = 0
    
    
    //上次缩合
    var prevScale       :CGFloat = 1.0
    //本次缩合
    var currentScale    :CGFloat = 1.0
    //缩合限制
    let sScaleMin        :CGFloat = 0.5
    let sScaleMax        :CGFloat = 5.0
    let camera_Fox       :Double  = 60.0
    let camera_Height    :Double  = 50.0
   //是否在进行手势操作
    var gestureDuring    :Bool    = false
    var rMatrix4 = SCNMatrix4Identity
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
        setUI()
        downloadImage()
    }
    
    fileprivate func downloadImage(){
        
        if let url = URL(string: "https://video.jmhz.programdog.fun/QUAN.jpg") {
            KingfisherManager.shared.retrieveImage(with: url) { [weak self] (result) in
                guard let self = self else {return}
                switch result {
                case .success(let imgResult):
                    print(imgResult.image)
                    self.panoramaNode.geometry?.firstMaterial?.diffuse.contents =  imgResult.image
                    break;
                case .failure(let error):
                    print(error)
                    break
                    
                }
            }
        }
        
    }

    fileprivate func setUI(){
        
        //创建SCNView 并加到 view上
        scnView = SCNView()
        scnView.frame = view.bounds
        scnView.scene = SCNScene()
        view.addSubview(scnView)

        //添加相机节点
        cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        cameraNode.camera?.automaticallyAdjustsZRange = true ///自动添加可视距离
        cameraNode.position =  SCNVector3(x: 0, y: 0, z: 0) ///相机位置中心点
        cameraNode.camera?.focalLength = camera_Fox;
        cameraNode.camera?.fieldOfView = camera_Fox;
        scnView.scene?.rootNode.addChildNode(cameraNode)
        
        ///添加图片显示节点
        panoramaNode = SCNNode() ///创建一个图片结点
        panoramaNode.geometry =  SCNSphere(radius: 100);///半径为100的球形
        panoramaNode.geometry?.firstMaterial?.cullMode = .front //剔除外表面
        panoramaNode.geometry?.firstMaterial?.isDoubleSided = false ///显示一个面
        panoramaNode.position = SCNVector3Make(0, 0, 0); ///中心点
        scnView.scene?.rootNode.addChildNode(panoramaNode)

//        panoramaNode.geometry?.firstMaterial?.diffuse.contents =  UIImage(named: "panorama_image")
        
//        添加手势
        let pan = UIPanGestureRecognizer(target: self, action: #selector(panImage(gesture:)))
        scnView.addGestureRecognizer(pan)

        let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinchGesture(gesture:)))
        pinch.delegate = self
        scnView.addGestureRecognizer(pinch)
//        
//        let rotate = UIRotationGestureRecognizer(target: self, action: #selector(rotateImage(sender:)))
//        rotate.delegate = self
//        scnView.addGestureRecognizer(rotate)
//        rotate.require(toFail:pinch )
    }
    
    @objc func rotateImage(sender:UIRotationGestureRecognizer){
        
        var rotation : CGFloat = sender.rotation
        print("=====\(rotation)")
//            //旋转角度CGAffineTransformMakeRotation,改变图像角度
//            im.transform = CGAffineTransformMakeRotation(rotation+netRotation)
//            //状态结束，保存数据
        if sender.state == UIGestureRecognizer.State.ended{
                netRotation += rotation
            }
    }
    
    @objc func panImage(gesture:UIGestureRecognizer){
        if !gesture.isKind(of: UIPanGestureRecognizer.self){
            return
        }

        if gesture.state == .began {
            gestureDuring = true
            let currentPoint = gesture.location(in: self.scnView)
            lastPoint_x = currentPoint.x
            lastPoint_y = currentPoint.y
        }else if gesture.state == .ended {
            gestureDuring = false
        }else{
            let currentPoint = gesture .location(in: self.scnView)
            var distX = currentPoint.x - lastPoint_x
            var distY:CGFloat = currentPoint.y - lastPoint_y
            lastPoint_x = currentPoint.x
            lastPoint_y = currentPoint.y
            distX *= -0.005 * 0.5
            distY *= -0.005 * 0.5
            if (abs(distX) > abs(distY)) {
            self.fingerRotationY += distX;
            }else {
            self.fingerRotationX += distY;
            }

            var modelMatrix = SCNMatrix4MakeRotation(0, 0, 0, 0)
            modelMatrix = SCNMatrix4Rotate(modelMatrix, Float(fingerRotationY),0, 1, 0);
            modelMatrix = SCNMatrix4Rotate(modelMatrix, Float(fingerRotationX), 1, 0, 0);
            self.cameraNode.pivot = modelMatrix;
        }
    }
    //捏合手势
    @objc func pinchGesture(gesture:UIGestureRecognizer){
        if !gesture.isKind(of: UIPinchGestureRecognizer.self){
            return
        }
        let pinchGesture = gesture as! UIPinchGestureRecognizer
        
        if pinchGesture.state != .ended && pinchGesture.state != .failed{
            if pinchGesture.scale != 0.0{
                
                var scale = pinchGesture.scale - 1
                if scale < 0 {
                    scale *= (sScaleMax - sScaleMin)
                }
                    currentScale = scale + prevScale
                    currentScale = validateScale(scale: currentScale)
                
                let valScale = validateScale(scale: currentScale)
                let scaleRatio = 1-(valScale-1)*0.15
                let xFov = CGFloat(camera_Fox) * scaleRatio
                let yFov = CGFloat(camera_Height) * scaleRatio
                    cameraNode.camera?.focalLength = Double(xFov)
                    cameraNode.camera?.fieldOfView = Double(yFov)
            }
            }else if pinchGesture.state == .ended{
            prevScale = currentScale
        }
        
    }
    
    private func validateScale(scale:CGFloat) -> CGFloat {
        var validateScale = scale
        if scale < sScaleMin {
            validateScale = sScaleMin
        } else if scale > sScaleMax{
            validateScale = sScaleMax
        }
        return validateScale
    }
   
    
}


extension ZFScnViewController:UIGestureRecognizerDelegate{

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}
